package com.itheima.wms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.wms.common.service.CrudServiceImpl;
import com.itheima.wms.common.utils.RelationUtils;
import com.itheima.wms.dao.*;
import com.itheima.wms.entity.OwnerLocationEntity;
import com.itheima.wms.entity.WarehouseEntity;
import com.itheima.wms.service.WarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 业务实现类
 * 仓库
 * </p>
 */
@Slf4j
@Service
public class WarehouseServiceImpl extends CrudServiceImpl<WarehouseMapper, WarehouseEntity> implements WarehouseService {

    private static List<Class> SERVICE = new ArrayList() {{
        add(AreaMapper.class);
        add(LocationMapper.class);
        add(GoodsMapper.class);
        add(ReceiptMapper.class);
        add(OutboundMapper.class);
        add(CheckMapper.class);
    }};

    @Autowired
    private OwnerLocationMapper ownerLocationMapper;

    @Override
    public List<WarehouseEntity> list(Map data) {
        if (data.containsKey("ownerId")) {
            Long ownerId = Long.valueOf(data.get("ownerId").toString());
            LambdaQueryWrapper<OwnerLocationEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(OwnerLocationEntity::getOwnerId, ownerId);
            List<OwnerLocationEntity> ownerLocationEntities = ownerLocationMapper.selectList(wrapper);
            Set<Long> wareahouseIdSet = ownerLocationEntities.stream().map(ownerLocationEntity -> ownerLocationEntity.getWarehouseId()).collect(Collectors.toSet());
            if (CollectionUtils.isEmpty(wareahouseIdSet)) {
                return new ArrayList<>(0);
            }
            data.put("in_id", wareahouseIdSet);
            data.remove("ownerId");
        }
        return super.list(data);
    }

    @Override
    @Cacheable(value = "WarehouseEntity")
    public WarehouseEntity getByName(String warehouse) {
        return getOne("name", warehouse);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        idList.forEach(id -> {
            RelationUtils.checkRelation(id, "warehouse_id", SERVICE);
        });
        return super.removeByIds(idList);
    }
}
